package com.zhengjiang.zboot.admin.service.impl;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import com.zhengjiang.zboot.admin.constant.SysConstants;
import org.springframework.stereotype.Service;
import com.zhengjiang.zboot.admin.dao.SysMenuMapper;
import com.zhengjiang.zboot.admin.model.SysMenu;
import com.zhengjiang.zboot.admin.service.SysMenuService;
import com.zhengjiang.zboot.core.page.MybatisPageHelper;
import com.zhengjiang.zboot.core.page.PageRequest;
import com.zhengjiang.zboot.core.page.PageResult;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;

@Service
public class SysMenuServiceImpl implements SysMenuService {

	@Resource
	private SysMenuMapper sysMenuMapper;

	@Override
	public int save(SysMenu record) {
		if(record.getId() == null || record.getId() == 0) {
			return sysMenuMapper.insertSelective(record);
		}
		if(record.getParentId() == null) {
			record.setParentId(0L);
		}
		return sysMenuMapper.updateByPrimaryKeySelective(record);
	}

	@Override
	public int delete(SysMenu record) {
		return sysMenuMapper.deleteByPrimaryKey(record.getId());
	}

	@Override
	public int delete(List<SysMenu> records) {
		for(SysMenu record:records) {
			delete(record);
		}
		return 1;
	}

	@Override
	public SysMenu findById(Long id) {
		return sysMenuMapper.selectByPrimaryKey(id);
	}

	@Override
	public PageResult findPage(PageRequest pageRequest) {
		return MybatisPageHelper.findPage(pageRequest, sysMenuMapper);
	}

	@Override
	public List<SysMenu> findTree(String userName, List<Integer> menuTypes) {
		List<SysMenu> userMenus = findByUser(userName);
		List<SysMenu> sysTreeMenus  = userMenus.stream().filter(t -> t.getParentId() == 0)
				.sorted(Comparator.comparing(SysMenu::getOrderNum))
				.map(t->{
					t.setLevel(0);
					return t;
				 }).collect(Collectors.toList());
		findMenuTree(sysTreeMenus,userMenus,menuTypes);
		return sysTreeMenus;
	}

	public void findMenuTree(List<SysMenu> parentMenus,List<SysMenu> allMenus,List<Integer> menuTypes){
		parentMenus.stream().forEach(t->{
			List<SysMenu> childMenus = allMenus.stream()
					.filter(e -> (e.getParentId() == t.getId() && menuTypes.contains(e.getType())))
					.map(o->{
						o.setParentName(t.getName());
						o.setLevel(t.getLevel() + 1);
						return o;
					}).collect(Collectors.toList());
			if (!CollectionUtils.isEmpty(childMenus)){
				findMenuTree(childMenus,allMenus,menuTypes);
			}
			t.setChildren(childMenus);
		});
	}

	@Override
	public List<SysMenu> findByUser(String userName) {
		if(StringUtils.isEmpty(userName) || SysConstants.ADMIN.equalsIgnoreCase(userName)) {
			return sysMenuMapper.findAll();
		}
		return sysMenuMapper.findByUserName(userName);
	}
}
